/**
 * 
 */
package vn.dailyticket.web.admin.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.view.UrlBasedViewResolver;

/**
 * Enrich the tiles view to be suitable with device type.
 * 
 * @author khoink
 * @author ptgamr
 */
public class TilesViewInterceptor extends HandlerInterceptorAdapter {

    private String tilesNamePrefix = ".dailyticket.web.admin.";

    /*
     * (non-Javadoc)
     * @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#postHandle
     * (javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object,
     * org.springframework.web.servlet.ModelAndView)
     */
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if (modelAndView == null || modelAndView.getViewName() == null || request == null) {
            // not all mandatory parameters given -> return
            return;
        }
        final String viewName = modelAndView.getViewName();

        if (!modelAndView.isReference() || viewName.startsWith(UrlBasedViewResolver.FORWARD_URL_PREFIX)
                || viewName.startsWith(UrlBasedViewResolver.REDIRECT_URL_PREFIX)) {
            // no tiles reference or redirect url -> just leave MAV as it is and
            // return
            return;
        }
        // use device resolver
        if (viewName.contains("/")) {
            // jsp view
            modelAndView.setViewName("/" + viewName);
        } else {
            modelAndView.setViewName(tilesNamePrefix + viewName);
        }
    }
}
